package com.huawei.struts.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.huawei.struts.util.PageBean;
import com.st.model.LjwPremissionT;
import com.st.model.LjwUserT;

/**
 * A data access object (DAO) providing persistence and search support for
 * LjwPremissionT entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see com.st.model.LjwPremissionT
 * @author MyEclipse Persistence Tools
 */

public class LjwPremissionTDAO extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(LjwPremissionTDAO.class);
	// property constants
	public static final String _RUID = "RUid";
	public static final String _RNAME = "RName";
	public static final String PR_UID = "prUid";
	public static final String PR_NAME = "prName";

	protected void initDao() {
		// do nothing
	}

	public void save(LjwPremissionT transientInstance) {
		log.debug("saving LjwPremissionT instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(List<LjwPremissionT> persistentInstance) {
		log.debug("deleting LjwPremissionT instance");
		try {
			getHibernateTemplate().deleteAll(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public LjwPremissionT findById(java.lang.Integer id) {
		log.debug("getting LjwPremissionT instance with id: " + id);
		try {
			LjwPremissionT instance = (LjwPremissionT) getHibernateTemplate()
					.get("com.st.model.LjwPremissionT", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(LjwPremissionT instance) {
		log.debug("finding LjwPremissionT instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding LjwPremissionT instance with property: "
				+ propertyName + ", value: " + value);
		try {
			String queryString = "from LjwPremissionT as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByRUid(Object RUid) {
		return findByProperty(_RUID, RUid);
	}

	public List findByRName(Object RName) {
		return findByProperty(_RNAME, RName);
	}

	public List findByPrUid(Object prUid) {
		return findByProperty(PR_UID, prUid);
	}

	public List findByPrName(Object prName) {
		return findByProperty(PR_NAME, prName);
	}

	public List findAll() {
		log.debug("finding all LjwPremissionT instances");
		try {
			String queryString = "from LjwPremissionT";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public LjwPremissionT merge(LjwPremissionT detachedInstance) {
		log.debug("merging LjwPremissionT instance");
		try {
			LjwPremissionT result = (LjwPremissionT) getHibernateTemplate()
					.merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(LjwPremissionT instance) {
		log.debug("attaching dirty LjwPremissionT instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(LjwPremissionT instance) {
		log.debug("attaching clean LjwPremissionT instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static LjwPremissionTDAO getFromApplicationContext(
			ApplicationContext ctx) {
		return (LjwPremissionTDAO) ctx.getBean("LjwPremissionTDAO");
	}
	
	public List<LjwPremissionT> findPremission(final int roleId) {
		
		List list = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				String sql="select t1.R_NAME RName,t1.PR_NAME prName," +
				 		"t1.PERMISSION_ID permissionId,if(t2.PERMISSION_ID>0,1,0) isChecked " +
				 		"from LJW_PREMISSION_T  t1 LEFT JOIN LJW_ACLENTRY_T t2 " +
				 		"on t1.PERMISSION_ID=t2.PERMISSION_ID and t2.ROLE_ID=?";
				 Connection con = session.connection();      
                 PreparedStatement ps = con.prepareStatement(sql);    
                 ps.setInt(1, roleId);
                 ResultSet rs = ps.executeQuery();  
                 List<LjwPremissionT> list = new ArrayList<LjwPremissionT>();
                 while(rs.next()){
                	 LjwPremissionT ljwPremission=new LjwPremissionT();
                	 ljwPremission.setRName(rs.getString("RName"));
                	 ljwPremission.setPrName(rs.getString("prName"));
                	 ljwPremission.setPermissionId(rs.getInt("permissionId"));
                	 ljwPremission.setIsChecked(rs.getInt("isChecked"));
                	 list.add(ljwPremission);
                 }
                 rs.close();
                 ps.close();
                 con.close();
				return list;
			}
		});
		return list;
	}
	
	public int checkExsits(final LjwPremissionT premission) {
		Integer count = (Integer)getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				StringBuffer hql=new StringBuffer();
				hql.append("select count(*) from LjwPremissionT u where 1=1");
				Query query=queryMap(hql,premission,session); 
				return  Integer.parseInt(query.iterate().next().toString());
			}
		});
		return Integer.parseInt(count.toString());
	}
	
	public  Query queryMap(final StringBuffer hql,final LjwPremissionT premission,Session session)
	{
		Map map=new HashMap();
		if(premission.getRUid()!=null)
		{
			map.put("rUid", premission.getRUid());
		    hql.append(" and u.RUid like :rUid");
		}
		if(premission.getPrUid()!=null)
		{
			map.put("prUid", premission.getPrUid());
		    hql.append(" and u.prUid like :prUid");
		}
		Query query = session.createQuery(hql.toString());
		
		Iterator it = map.keySet().iterator();

         while (it.hasNext()){

         Object key = it.next(); 

         query.setParameter(key.toString(), map.get(key)); 

         }
         return query;
	}
}